// upLoaderImg.js
import axios from 'axios'		// 引入axios

export default {
    upLoaderImg: function (file) {
        return new Promise((resolve, reject) => {
            // file是当前file对象, 此对象包含file和content
            const formData = new FormData()
            let fileSize = 0
            if (file.file.size) {
                fileSize = file.file.size
            }
            // 上传超过5M（5*1024*1024kb）的进行压缩
            if (fileSize > 26214400) {
                const canvas = document.createElement('canvas') // 创建Canvas对象(画布)
                const context = canvas.getContext('2d')
                const img = new Image()
                img.src = file.content // 指定图片的DataURL(图片的base64编码数据)
                img.onload = () => {
                    let width = img.width
                    let height = img.height
                    // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
                    let ratio
                    if ((ratio = (width * height) / 4000000) > 1) {
                        ratio = Math.sqrt(ratio)
                        width /= ratio
                        height /= ratio
                    }
                    canvas.width = width
                    canvas.height = height
                    context.drawImage(img, 0, 0, width, height)
                    file.content = canvas.toDataURL(file.file.type, 0.92) // 0.92为默认压缩质量
                    const files = this.dataURLtoFile(file.content, file.file.name)
                    formData.append('file', files)
                    resolve(this.upload(formData))
                }
            } else {
                formData.append('file', file.file)
                resolve(this.upload(formData))
            }
        })
    },

    // 将base64转换为file文件
    dataURLtoFile: function (dataurl, filename) {
        const arr = dataurl.split(',')
        const mime = arr[0].match(/:(.*?);/)[1]
        const bstr = atob(arr[1])
        let n = bstr.length
        const u8arr = new Uint8Array(n)
        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], filename, { type: mime })
    },

    upload: function (formData) {
        // this.axios 是因为在main.js写在vue实例里
        const axiosMy = axios.create({
            timeout: 15000, // 请求超时时间
            headers: {// 这里可设置所有的请求头
                'Content-Type': 'application/x-www-form-urlencoded' // 该项建议设置 如果未 POST请求时 数据未做处理时会出现错误，最理想的解决方法就是 直接设置该项
            },
            crossDomain: true,
            xhrFields: {
                withCredentials: true
            },
            transformRequest: [
                (data, headers) => {
                    delete headers.common['X-CSRF-TOKEN']
                    return data
                }
            ]
        })
        return new Promise((resolve, reject) => {
            axiosMy.post(
                'https://file.suofeiyahome.com/upload',
                formData,
                {
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    }
                }
            )
                .then(res => {
                    const data = res.data
                    if (data.code === 0) {
                        resolve({
                            default: data.data.url
                        })
                    } else {
                        reject(data.message)
                    }
                })
                .catch(err => {
                    reject(err)
                })
        })
    }
}
